package com.atguigu.gmall.realtime.common.util;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;

public class HBaseUtil {
    public static Connection getHBaseConnection(){
        try {
            Configuration conf = new Configuration();
            conf.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104");
            return ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void closeHBaseConnection(Connection hbaseConn){
        if (hbaseConn != null && !hbaseConn.isClosed()){
            try {
                hbaseConn.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void createHBaseTable(Connection hbaseConn, String nameSpace, String tableName, String...families){
        if (families.length < 1){
            System.out.println("建表操作必须至少提供一个列族");
            return;
        }
        try (Admin admin = hbaseConn.getAdmin()){
            TableName tableNameObj = TableName.valueOf(nameSpace, tableName);
            if (admin.tableExists(tableNameObj)){
                System.out.println("要创建的表空间" + nameSpace + "下的表" + tableName + "已经存在");
                return;
            }
            TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableNameObj);
            for (String family : families) {
                tableDescriptorBuilder.setColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(family)).build());
            }
            admin.createTable(tableDescriptorBuilder.build());
            System.out.println("表空间" + nameSpace + "下的表" + tableName + "创建成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void dropHBaseTable(Connection hbaseConn, String nameSpace, String tableName){
        try (Admin admin = hbaseConn.getAdmin()){
            TableName tableNameObj = TableName.valueOf(nameSpace, tableName);
            if (!admin.tableExists(tableNameObj)){
                System.out.println("要删除的表空间" + nameSpace + "下的表" + tableName + "不存在");
                return;
            }
            admin.disableTable(tableNameObj);
            admin.deleteTable(tableNameObj);
            System.out.println("表空间" + nameSpace + "下的表" + tableName + "删除成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *向HBase表中put数据
     * @param hbaseConn 连接
     * @param nameSpace 表空间
     * @param tableName 表名
     * @param rowKey rowkey
     * @param family 列族
     * @param jsonObj 要同步的json
     */
    public static void putRow(Connection hbaseConn, String nameSpace, String tableName, String rowKey, String family, JSONObject jsonObj){
        TableName tableNameObj = TableName.valueOf(nameSpace, tableName);
        try (Table table = hbaseConn.getTable(tableNameObj)){
            Put put = new Put(Bytes.toBytes(rowKey));
            Set<String> keys = jsonObj.keySet();
            for (String columnName : keys) {
                String columnValue = jsonObj.getString(columnName);
                if (StringUtils.isNotEmpty(columnValue)){
                    put.addColumn(Bytes.toBytes(family), Bytes.toBytes(columnName), Bytes.toBytes(columnValue));
                }
            }
            table.put(put);
            System.out.println("向表空间" + nameSpace + "的表" + tableName + "中put数据" + rowKey + "成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //从HBase表中删除数据
    public static void delRow(Connection hbaseConn, String nameSpace, String tableName, String rowKey){
        TableName tableNameObj = TableName.valueOf(nameSpace, tableName);
        try (Table table = hbaseConn.getTable(tableNameObj)) {
            Delete delete = new Delete(Bytes.toBytes(rowKey));
            table.delete(delete);
            System.out.println("从表空间" + nameSpace + "的表" + tableName + "中删除数据" + rowKey + "成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //创建异步连接
    public static AsyncConnection getAsyncHBaseConnection(){
        try {
            Configuration conf = new Configuration();
            conf.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104");
            return ConnectionFactory.createAsyncConnection(conf).get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //关闭异步连接
    public static void closeAsyncHBaseConnection(AsyncConnection asyncHBaseConnection){
        if (asyncHBaseConnection != null){
            try {
                asyncHBaseConnection.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //通过异步连接从HBase读取数据
    public static <T> T readDimAsync(AsyncConnection hbaseConn, String nameSpace, String tableName, String rowKey, Class<T> clz, boolean... isUnderlineToCamel){
        boolean defaultIsUToC = false;
        if (isUnderlineToCamel.length > 0){
            defaultIsUToC = isUnderlineToCamel[0];
        }
        try {
            TableName tableNameObj = TableName.valueOf(nameSpace, tableName);
            AsyncTable<AdvancedScanResultConsumer> table = hbaseConn.getTable(tableNameObj);
            Get get = new Get(Bytes.toBytes(rowKey));
            Result result = table.get(get).get();
            List<Cell> cells = result.listCells();
            if (cells != null && cells.size() > 0){
                T obj = clz.newInstance();
                for (Cell cell : cells) {
                    String columnName = Bytes.toString(CellUtil.cloneQualifier(cell));
                    String columnValue = Bytes.toString(CellUtil.cloneValue(cell));
                    if(defaultIsUToC){
                        columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName);
                    }
                    //给对象的属性赋值
                    BeanUtils.setProperty(obj,columnName,columnValue);
                }
                return obj;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    public static void main(String[] args) {
        JSONObject jsonObj = readDimAsync(getAsyncHBaseConnection(), Constant.HBASE_NAMESPACE, "dim_sku_info", "1", JSONObject.class);
        String skuName = jsonObj.getString("sku_name");
        System.out.println(skuName);
    }
}
